<template>
	<div id="WriteArticles">
		<div class="container" v-show="!reWriteVisible">
			<el-form ref="Articleform" :model="Articleform" label-width="100px" :rules="rules">
				<div class="plugins-tips">
					<el-form-item label="标题:" prop="title">
						<el-input v-model="Articleform.title" placeholder="请输入文章标题" class="handle-input mr10"></el-input>
					</el-form-item>
				</div>
				<div prop="article_content">
					<quill-editor ref="myTextEditor" v-model="Articleform.article_content" :options="editorOption"></quill-editor>
				</div>
				<div style="margin: 0.625rem 0 0 0;">
					<!-- <el-form ref="Articleform" :model="Articleform" label-width="80px"> -->
					<el-form-item label="摘要:" prop="summary">
						<el-input type="textarea" :rows="2" placeholder="摘要" v-model="Articleform.summary"></el-input>
					</el-form-item>
					<el-form-item label="文章分类" prop="article_category">
						<el-select v-model="Articleform.article_category" placeholder="请选择">
							<el-option v-for="item in article_categoryOptions" :key="item.article_category_id" :label="item.title" :value="item.article_category_id">
							</el-option>
						</el-select>
					</el-form-item>
					<el-form-item label="分类栏目:" prop="article_sub_categorys_tree">
						<el-cascader :options="article_sub_categorys" v-model="Articleform.article_sub_categorys_tree" change-on-select></el-cascader>
					</el-form-item>
					<el-form-item label="文章隐私" prop="article_model">
						<el-radio-group v-model="Articleform.article_model">
							<el-radio label="1">公开</el-radio>
							<el-radio label="0">私有</el-radio>
						</el-radio-group>
					</el-form-item>
					<el-form-item label="标签" prop="meta_keywords">
						<el-input type="textarea" :rows="2" placeholder="标签(逗号隔开)" v-model="Articleform.meta_keywords"></el-input>
					</el-form-item>
					<el-form-item label="图片">
						<el-upload :action="imgUrl" list-type="picture-card" limit="1" multiple="false" :on-preview="handlePictureCardPreview"
						 :on-remove="handleRemove" :before-upload="beforeAvatarUpload" :on-success="handleAvatarSuccess" :file-list="file_list">
							<i class="el-icon-plus"></i>
						</el-upload>
						<el-dialog :visible.sync="dialogVisible" size="tiny">
							<img width="100%" :src="dialogImageUrl" alt="">
						</el-dialog>
					</el-form-item>
					<el-form-item>
						<el-button class="editor-btn" type="primary" @click="saveEdit('Articleform')">发布</el-button>
					</el-form-item>
				</div>
			</el-form>
		</div>

		<!-- 删除提示框 -->
		<div v-show="reWriteVisible">
			<div align="middle" style="padding-top: 10%;">
				<div style="color: #13CE66;font-size: 5.25rem;font-weight: bolder;">发布成功
					<i class="el-icon-success" style="color: #13CE66;"></i></div>
				<div style="padding-top: 10%;">
					<el-button @click="reWirteClick()">再写一篇</el-button>
					<el-button type="primary" @click="linkToListClick()">查看文章列表</el-button>
				</div>
			</div>
		</div>
	</div>
</template>

<script>
	import 'quill/dist/quill.core.css';
	import 'quill/dist/quill.snow.css';
	import 'quill/dist/quill.bubble.css';
	import common from '../../common/common.js'
	import {
		constHelp
	} from '../../common/contant';
	import {
		quillEditor,
		// Quill
	} from 'vue-quill-editor';
	import * as Quill from 'quill' //引入编辑器
	import {
		container,
		ImageExtend,
		QuillWatch
	} from 'quill-image-extend-module'
	Quill.register('modules/ImageExtend', ImageExtend)
	import bus from '../../common/bus';
	export default {
		name: 'Article_Content_VueEditor',
		data: function() {
			return {
				userInfo: {},
				content: '',
				reWriteVisible: false, //是否再写一篇
				editorOption: {
					modules: {
						ImageExtend: {
							loading: true, // 可选参数 是否显示上传进度和提示语
							name: 'img', // 图片参数名
							size: 3, // 可选参数 图片大小，单位为M，1M = 1024kb
							action: constHelp['WEBAPIURL'] + '/blogManage/upload', //服务器地址, 如果action为空，则采用base64插入图片
							// response 为一个函数用来获取服务器返回的具体图片地址
							// 例如服务器返回{code: 200; data:{ url: 'baidu.com'}}
							// 则 return res.data.url
							response: (res) => {
								return res.data.url;
							},
							headers: (xhr) => {}, // 可选参数 设置请求头部
							start: () => {}, // 可选参数 自定义开始上传触发事件
							end: () => {}, // 可选参数 自定义上传结束触发的事件，无论成功或者失败
							error: () => {}, // 可选参数 自定义网络错误触发的事件
							change: (xhr, formData) => {} // 可选参数 选择图片触发，也可用来设置头部，但比headers多了一个参数，可设置formData
						},
						toolbar: {
							handlers: {
								'image': function() {
									QuillWatch.emit(this.quill.id)
								}
							},
							container: [
								["bold", "italic", "underline", "strike"], // 加粗 斜体 下划线 删除线
								["blockquote", "code-block"], // 引用  代码块
								[{
									header: 1
								}, {
									header: 2
								}], // 1、2 级标题
								[{
									list: "ordered"
								}, {
									list: "bullet"
								}], // 有序、无序列表
								[{
									script: "sub"
								}, {
									script: "super"
								}], // 上标/下标
								[{
									indent: "-1"
								}, {
									indent: "+1"
								}], // 缩进
								// [{'direction': 'rtl'}],                         // 文本方向
								[{
									size: ["small", false, "large", "huge"]
								}], // 字体大小
								[{
									header: [1, 2, 3, 4, 5, 6, false]
								}], // 标题
								[{
									color: []
								}, {
									background: []
								}], // 字体颜色、字体背景颜色
								[{
									font: []
								}], // 字体种类
								[{
									align: []
								}], // 对齐方式
								["clean"], // 清除文本格式
								["link", "image", "video"] // 链接、图片、视频
							], //工具菜单栏配置
						}
					},
					placeholder: '请在这里留下您的痕迹', //提示
					readyOnly: false, //是否只读
					theme: 'snow', //主题 snow/bubble
					syntax: true, //语法检测
				},
				"insertUpdateflage": 0,
				url: {
					// 添加文章
					insert_article: constHelp['WEBAPIURL'] + '/blogManage/insert_article',
					// 编辑文章
					update_article: constHelp['WEBAPIURL'] + '/blogManage/update_article',
					// 获取文章类型
					get_article_category_all_list: constHelp['WEBAPIURL'] + '/articleCategory/get_article_category_all_list',
					getTree: constHelp['WEBAPIURL'] + '/articleCategory/get_article_category_tree_all_list', // 获取文章类型列表
				},
				"Articleform": this.$route.params,
				mainTreeData: [],
				ArticleTypeOptions: [], //下拉框数据
				ArticlePersonalTypeOptions: [], //下拉框数据
				article_categoryOptions: [],
				article_sub_categorys: [],
				rules: {
					title: [{
							required: true,
							message: '请输入文章标题',
							trigger: 'blur'
						},
						{
							max: 100,
							message: '长度在100个字符',
							trigger: 'blur'
						}
					],
					article_content: [{
						required: true,
						message: '请输入文章内容!',
						trigger: 'change'
					}],
					summary: [{
						required: true,
						message: '请输入摘要!',
						trigger: 'blur'
					}],
					article_category: [{
						required: true,
						message: '选中文章分类!',
						trigger: 'blur'
					}],
					article_sub_categorys_tree: [{
						required: true,
						message: '选中文章分类栏目!',
						trigger: 'blur'
					}],
					article_model: [{
						required: true,
						message: '请选择文章隐私类型!',
						trigger: 'blur'
					}],
					meta_keywords: [{
						required: true,
						message: '请输入标签,并且用逗号隔开!',
						trigger: 'blur'
					}]
				},
				imageUrl: '',
				dialogImageUrl: '',
				dialogVisible: false,
				imgUrl: constHelp['WEBAPIURL'] + '/blogManage/upload_icon',
				file_list: []
			}
		},
		created() {
			// this.getTreeData();
			// this.ArticleTypecombox();
			// this.ArticlePersonalTypecombox();
			let userInfo_string = localStorage.getItem("UserInfo");
			if (!common.IsNull(userInfo_string)) {
				this.userInfo = JSON.parse(userInfo_string);
			}

			this.Articleform = this.$route.params;
			this.Articleform.article_category = this.$route.params.article_category
			if (!common.IsNull(this.Articleform) && !common.IsNull(this.Articleform.title)) {
				this.insertUpdateflage = "1"
				this.file_list = [{
					url: this.Articleform.link_to
				}]
			}
			this.article_category_Type_combox()
			this.init_article_sub_categorys()
		},
		components: {
			quillEditor
		},
		methods: {
			// 加载分类栏目
			init_article_sub_categorys() {
				this.$axios.post(this.url.getTree, {
					user_id: this.userInfo.user_Id
				}, {
					withCredentials: true
				}).then((res) => {
					if (res.data.data != null && res.data.data != "") {
						this.article_sub_categorys = res.data.data;
					}
				})
			},
			//加载分类类型
			article_category_Type_combox() {
				this.$axios.post(this.url.get_article_category_all_list, {
					user_id: this.userInfo.user_Id
				}, {
					withCredentials: true
				}).then((res) => {
					if (res.data.data != null) {
						this.article_categoryOptions = res.data.data;
					}
				})
			},
			handleRemove(file, fileList) {
				console.log(file, fileList);
			},
			handlePictureCardPreview(file) {
				this.dialogImageUrl = file.url;
				this.dialogVisible = true;
			},

			beforeAvatarUpload(file) {
				// const isJPG = file.type === 'image/jpeg';
				const isLt2M = file.size / 1024 / 1024 < 2;

				// if (!isJPG) {
				// 	this.$message.error('上传头像图片只能是 JPG 格式!');
				// }
				if (!isLt2M) {
					this.$message.error('上传头像图片大小不能超过 2MB!');
				}
				return isLt2M;
				// return isJPG && isLt2M;
			},
			handleAvatarSuccess(response, file, fileList) {
				this.imageUrl = response.data.url;
			},
			// 获取菜单树
			getTreeData() {
				this.$axios.post(this.url.getTree, {
					user_id: this.userInfo.user_Id
				}, {
					withCredentials: true
				}).then((res) => {
					if (res.data.data != null) {
						this.mainTreeData = res.data.data;
					}
				})
			},
			ArticleTypecombox() {
				this.$axios.post(this.url.ArticleTypeombox, {
					withCredentials: true
				}).then((res) => {
					if (res.data.data != null) {
						this.ArticleTypeOptions = res.data.data;
					}
				})
			},

			ArticlePersonalTypecombox() {
				this.$axios.post(this.url.getArticlePersonalTypeLists, {
					withCredentials: true
				}).then((res) => {
					if (res.data.data != null) {
						this.ArticlePersonalTypeOptions = res.data.data;
					}
				})
			},
			// 保存编辑 
			saveEdit(formName) {
				this.Articleform.user_id = this.userInfo.user_Id
				this.$refs[formName].validate((valid) => {
					if (valid) {
						this.Articleform.link_to = this.imageUrl
						let chapterParentId;
						if (!common.IsNull(this.Articleform.article_sub_categorys_tree)) {
							this.Articleform.article_sub_category = this.Articleform.article_sub_categorys_tree[this.Articleform.article_sub_categorys_tree
								.length - 1];
							this.Articleform.article_sub_categorys = this.Articleform.article_sub_categorys_tree.join(",")
						}
						var saveUrl = this.insertUpdateflage == 0 ? this.url.insert_article : this.url.update_article;

						this.$axios.post(saveUrl, this.Articleform, {
							withCredentials: true
						}).then((res) => {
							// alert(JSON.stringify(res.data))
							if (res.data.err == "0") {
								this.reWriteVisible = true
								this.$message.success("保存成功");
							} else {
								this.$message.success("保存失败");
							}
						}).catch((response) => {
							this.$message.success('修改失败');
						})
					} else {
						return false;
					}
				});
			},
			onEditorChange({
				editor,
				html,
				text
			}) {
				this.content = html;
			},
			submit() {
				console.log(this.content);
				this.$message.success('提交成功！');
			},
			// 再写一篇
			reWirteClick() {
				this.Articleform = {}
				this.article_category_Type_combox()
				this.init_article_sub_categorys()
				this.reWriteVisible = false
			},
			// 查看文章列表
			linkToListClick() {
				this.$router.push({
					path: '/ArticleSearch',
					name: 'ArticleSearch',
				})
			}

		}
	}
</script>
<style scoped>
	.avatar-uploader .el-upload {
		border: 1px dashed #d9d9d9;
		border-radius: 6px;
		cursor: pointer;
		position: relative;
		overflow: hidden;
	}

	.avatar-uploader .el-upload:hover {
		border-color: #409EFF;
	}

	.avatar-uploader-icon {
		font-size: 28px;
		color: #8c939d;
		width: 178px;
		height: 178px;
		line-height: 178px;
		text-align: center;
	}

	.avatar {
		width: 178px;
		height: 178px;
		display: block;
	}

	.editor-btn {
		margin-top: 20px;
	}
</style>
